package cn.itcast.service.cargo.impl;

import cn.itcast.dao.cargo.ContractDao;
import cn.itcast.dao.cargo.ExtCproductDao;
import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ExtCproduct;
import cn.itcast.domain.cargo.ExtCproductExample;
import cn.itcast.service.cargo.ExtCproductService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.UUID;

@Service
public class ExtCproductServiceImpl implements ExtCproductService {

 @Autowired
 private ExtCproductDao extCproductDao;

 @Autowired
 private ContractDao contractDao;

 //保存
 public void save(ExtCproduct ec) {
  //计算保存附件的总金额
  double newMoney = 0.0;
  if (ec.getPrice() != null && ec.getCnumber() != null) {
   newMoney = ec.getPrice() * ec.getCnumber();
  }
  ec.setAmount(newMoney);
  //设置附件的id
  ec.setId(UUID.randomUUID().toString());
  //保存附件
  extCproductDao.insertSelective(ec);
  //根据合同id查询购销合同
  Contract contract = contractDao.selectByPrimaryKey(ec.getContractId());
  //设置合同的总金额
  contract.setTotalAmount(contract.getTotalAmount() + newMoney);
  //设置合同附件数
  contract.setExtNum(contract.getExtNum() + 1);
  //更新合同
  contractDao.updateByPrimaryKeySelective(contract);
 }

 //更新
 public void update(ExtCproduct ec) {
  //设置修改之后的总金额
  double newMoney = 0.0;
  if (ec.getPrice() != null && ec.getCnumber() != null) {
   newMoney = ec.getPrice() * ec.getCnumber();
  }
  ec.setAmount(newMoney);
  //查询修改之前的总金额
  ExtCproduct oldEc = extCproductDao.selectByPrimaryKey(ec.getId());
  double oldMoney = oldEc.getAmount();
  //更新购销合同
  extCproductDao.updateByPrimaryKeySelective(ec);
  //根据合同id查询购销合同
  Contract contract = contractDao.selectByPrimaryKey(ec.getContractId());
  //设置合同总金额
  contract.setTotalAmount(contract.getTotalAmount() - oldMoney + newMoney);
  //更新合同
  contractDao.updateByPrimaryKeySelective(contract);
 }

 //删除
 public void delete(String id) {
  //根据附件id查询附件对象
  ExtCproduct extCproduct = extCproductDao.selectByPrimaryKey(id);
  //删除附件
  extCproductDao.deleteByPrimaryKey(id);
  //根据合同id查询
  Contract contract = contractDao.selectByPrimaryKey(extCproduct.getContractId());
  //修改合同的总金额
  contract.setTotalAmount(contract.getTotalAmount() - extCproduct.getAmount());
  //修改附件数
  contract.setExtNum(contract.getExtNum() - 1);
  //更新合同
  contractDao.updateByPrimaryKeySelective(contract);
 }

 //根据id查找
 public ExtCproduct findById(String id) {
  return extCproductDao.selectByPrimaryKey(id);
 }

 //分页查询
 public PageInfo findAll(ExtCproductExample example, int page, int size) {
  PageHelper.startPage(page, size);
  List<ExtCproduct> list = extCproductDao.selectByExample(example);
  return new PageInfo(list);
 }
}
